/* eslint-disable no-param-reassign */
import { computed, defineComponent, Ref, ref, watch } from 'vue';
import {
  getEditorEmits,
  getInputIpProps,
  useNamespace,
} from '@ibiz-template/vue3-util';
import './ibiz-input-ip.scss';
import { TextBoxEditorController } from '../text-box-editor.controller';

export const IBizInputIP = defineComponent({
  name: 'IBizInputIP',
  props: getInputIpProps<TextBoxEditorController>(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('input-ip');

    const c = props.controller;

    // 是否显示表单默认内容
    const showFormDefaultContent = computed(() => {
      if (
        props.controlParams &&
        props.controlParams.editmode === 'hover' &&
        !props.readonly
      ) {
        return true;
      }
      return false;
    });

    // 获取当前值
    const currentVal = ref<string[]>([]);

    // 当前组件是否已获取到焦点
    const activeElement = ref(false);

    // 当前组件输入框是否全部失焦
    const isAllBlur = ref(false);

    // 四段ip
    const firstIp = ref('');
    const secIp = ref('');
    const thirdIp = ref('');
    const forIp = ref('');

    // 初始赋值
    if (props.value) {
      const ipArr = props.value.split('.');
      currentVal.value = ipArr;
      firstIp.value = currentVal.value[0];
      secIp.value = currentVal.value[1];
      thirdIp.value = currentVal.value[2];
      forIp.value = currentVal.value[3];
    }

    // 验证格式
    const checkIpVal = (
      newVal: string,
      oldVal: string,
      ip: Ref<string>,
      index: number,
    ) => {
      if (newVal === '') return;
      const reg = /^(([0-9]|([1-9]\d)|(1\d\d)|(2([0-4]\d|5[0-5]))))$/g;
      if (reg.test(newVal)) {
        currentVal.value[index] = newVal;
      } else if (ip) {
        ibiz.message.warning(`ip格式验证未通过，第${index + 1}段ip重置回旧值`);
        ip.value = oldVal;
        currentVal.value[index] = oldVal;
      }
      if (firstIp.value && secIp.value && thirdIp.value && forIp.value) {
        emit(
          'change',
          `${firstIp.value}.${secIp.value}.${thirdIp.value}.${forIp.value}`,
        );
      }
    };

    // 监听每段IP变化
    watch(firstIp, (newVal: string, oldVal: string) => {
      checkIpVal(newVal, oldVal, firstIp, 0);
    });
    watch(secIp, (newVal: string, oldVal: string) => {
      checkIpVal(newVal, oldVal, secIp, 1);
    });
    watch(thirdIp, (newVal: string, oldVal: string) => {
      checkIpVal(newVal, oldVal, thirdIp, 2);
    });
    watch(forIp, (newVal: string, oldVal: string) => {
      checkIpVal(newVal, oldVal, forIp, 3);
    });

    // 输入框获取到焦点时设置该组件已获取到焦点
    const getFocus = () => {
      activeElement.value = true;
      if (isAllBlur.value) {
        isAllBlur.value = false;
        emit('focus');
      }
    };

    // 失焦事件
    const blur = () => {
      activeElement.value = false;
      setTimeout(() => {
        if (!activeElement.value) {
          isAllBlur.value = true;
          emit('blur');
        }
      }, 0);
    };

    // 处理点击键盘
    const handleKeyUp = (e: KeyboardEvent) => {
      if (e && e.code === 'Enter') {
        emit('enter', e);
      }
    };

    return {
      ns,
      c,
      currentVal,
      getFocus,
      blur,
      firstIp,
      secIp,
      thirdIp,
      forIp,
      showFormDefaultContent,
      handleKeyUp,
    };
  },
  render() {
    return (
      <div
        class={[
          this.ns.b(),
          this.disabled ? this.ns.m('disabled') : '',
          this.readonly ? this.ns.m('readonly') : '',
          this.ns.is('show-default', this.showFormDefaultContent),
        ]}
      >
        <el-input
          type='text'
          size='small'
          disabled={this.disabled}
          readonly={this.readonly}
          onFocus={this.getFocus}
          onBlur={this.blur}
          onKeyup={this.handleKeyUp}
          maxlength={3}
          v-model={this.firstIp}
        />
        .
        <el-input
          type='text'
          size='small'
          disabled={this.disabled}
          readonly={this.readonly}
          onFocus={this.getFocus}
          onBlur={this.blur}
          onKeyup={this.handleKeyUp}
          maxlength={3}
          v-model={this.secIp}
        />
        .
        <el-input
          type='text'
          size='small'
          disabled={this.disabled}
          readonly={this.readonly}
          onFocus={this.getFocus}
          onBlur={this.blur}
          onKeyup={this.handleKeyUp}
          maxlength={3}
          v-model={this.thirdIp}
        />
        .
        <el-input
          type='text'
          size='small'
          disabled={this.disabled}
          readonly={this.readonly}
          onFocus={this.getFocus}
          onBlur={this.blur}
          onKeyup={this.handleKeyUp}
          maxlength={3}
          v-model={this.forIp}
        />
      </div>
    );
  },
});
